import uuid

from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

from app01.models import *
from django.conf import settings
import random
from app01.form.bootstrap import BootStrap


class App01ModleForm(BootStrap, forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.fields['id'].initial = uuid.uuid4()

    id = forms.UUIDField(widget=forms.HiddenInput(), required=False)
    name = forms.CharField(label="出版社名字",
                           widget=forms.TextInput(),
                           )
    address = forms.CharField(
        label='出版社地址',
        widget=forms.TextInput(),
    )

    def clean_id(self):
        id = self.cleaned_data.get('id')
        return id

    def clean_name(self):
        name = self.cleaned_data.get('name')
        exists = Publisher.objects.filter(name=name).exists()
        if exists:
            raise ValidationError('已有该出版社信息，请重新校验')
        return name

    def clean_address(self):
        address = self.cleaned_data.get('address')
        nessecery = ['市', '省', '区', '县', '旗', '村']
        if not any(char in address for char in nessecery):
            raise ValidationError("请正确填写地址")
        return address

    class Meta:
        model = Publisher
        fields = ["name", "address"]


class BookModleForm(BootStrap, forms.ModelForm):
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.fields['id'].initial = uuid.uuid4()

    id = forms.UUIDField(widget=forms.HiddenInput(), required=False)
    def clean_name(self):
        name = self.cleaned_data.get('name')
        return name

    def clean_price(self):
        price = self.cleaned_data.get('price')
        if price < 0:
            raise ValidationError("价格不能为负数")
        return price

    def clean_inventory(self):
        inventory = self.cleaned_data.get('inventory')
        if inventory <= 0 :
            raise ValidationError("新增图书时数量不能为负或者0")
        return inventory

    def clean_sale_num(self):
        sale_num = self.cleaned_data.get('sale_num')
        if sale_num<0:
            raise ValidationError("已售出数量不能为0")
        return sale_num

    class Meta:
        model = Book
        fields = ["name", "price", "inventory", "sale_num"]
